$(function () {

    intApiTreeTable();

    initEvent();

    $('.prompt-popover').popover({
        container: 'body'
    });
});

function initEvent() {
    //查询
    $("#apiSearch").on("click",".search",function (event) {
        $("#apiTable").bootstrapTreeTable("refresh");
    });
    //新增
    $("#apiSearch").on("click",".add",function (event) {
        var url = "/pages/dms/sqlStatement.html";
        $('#navbar').bootstrapNavbar("load",url,{});
    });
    //导出
    $("#apiSearch").on("click",".export",function (event) {
        var selections  =  $("#apiTable").bootstrapTreeTable("getSelections");
        var uids = selections.map(function (value,index,array){
            return value.uid;
        });
        var json = $("#apiSearch").serializable();
        json.uids = uids;
        $.ajax({
            url: '/dms/export',
            type: 'post',
            contentType: "application/json",
            xhrFields: {
                responseType: "blob"
            },
            data: JSON.stringify(json),
            success: function (data, status, xhr) {
                var  contentDisposition = xhr.getResponseHeader("Content-Disposition");
                var filename = contentDisposition.replace('attachment;filename=', '');
                var link = document.createElement('a'); // 创建一个a标签
                var url = window.URL.createObjectURL(data); // 将Blob对象转换为可下载的链接
                link.href = url;
                link.download = filename; // 设置下载的文件名
                link.click(); // 模拟点击链接进行下载
                window.URL.revokeObjectURL(url);
            }
        });
    });
    //导入-文件选择
    $("#apiSearch").on("change","#importFile",function (event) {
        var filename = $(this).val();
        filename = filename.substring(filename.lastIndexOf("\\")+1);
        $("#fileName").show().attr("title",filename).text(filename);
    });
    //导入-文件上传
    $("#apiSearch").on("click",".fileinput-import",function (event) {
        var files = $('#importFile')[0].files
        // 2. 判断是否选择了文件
        if (files.length <= 0) {
            return alert('请选择文件上传后再导入！');
        }
        var fd = new FormData();
        fd.append('file', files[0]);
        // 发起 jQuery 的 Ajax 请求，上传文件
        $.ajax({
            method: 'POST',
            url: '/dms/import',
            data: fd,
            processData: false,
            contentType: false,
            success: function (response) {
                $("#fileName").hide();
                $("#apiTable").bootstrapTreeTable("refresh");
            },
            error : function () {
                var arg = arguments;
                alert("上传失败");
            }
        });
    });
    //预览打印
    $("#apiSearch").on("click",".print",function (event) {
        var selections  =  $("#apiTable").bootstrapTreeTable("getSelections");
        var uids = selections.map(function (value,index,array){
            return value.uid;
        });
        var json = $("#apiSearch").serializable();
        json.uids = uids;
        var url = "/pages/dms/api/api.html";
        //忽略空值
        json =  Object.keys(json).reduce(function(acc, key) {
            if (json[key] !== null && json[key] !== undefined && json[key] !== '' && !(typeof json[key] === 'object' && Object.keys(json[key]).length === 0)) {
                acc[key] = json[key];
            }
            return acc;
        }, {});
        //查询表达没有筛选项，或选表格中项，根据选中的树形菜单选中项查询
        if(Object.keys(json).length === 0){
            var id = $("#apiMenuSelectedId").val();
            if(id){
                json.id = id;
            }
        }
        var param = $.param(json);
        window.open(url+"?"+param);
    });
    //编辑
    $("#apiTable").on("click",".edit",function (event) {
        var rid = $(this).attr("rid");
        var url = "/pages/dms/sqlStatement.html";
        $('#navbar').bootstrapNavbar("load",url,{id:rid});
    });

    //MOKE
    $("#apiTable").on("click",".mock",function (event) {
        var id = $(this).attr("rid");
        $.ajax({
            method: 'POST',
            url: '/dms/mock',
            data: {"id":id},
            success: function (response) {


                var html = "<form>" +
                    "<div className=\"form-group row\">" +
                    "<label htmlFor=\"methods\" className=\"col-sm-3 col-form-label required\">请求头</label>" +
                    "<div className=\"col-sm-9\">" +
                    "<pre><code class='form-control'>"+JSON.stringify(response.inputHead,null,4)+"</code></pre>" +
                    "</div></div>" +

                    "<div className=\"form-group row\">" +
                    "<label htmlFor=\"methods\" className=\"col-sm-3 col-form-label required\">请求参数</label>" +
                    "<div className=\"col-sm-9\">" +
                    "<pre><code class='form-control'>"+JSON.stringify(response.inputParameter,null,4)+"</code></pre>" +
                    "</div></div>" +


                    "<div className=\"form-group row\">" +
                    "<label htmlFor=\"methods\" className=\"col-sm-3 col-form-label required\">响应结果</label>" +
                    "<div className=\"col-sm-9\">" +
                    "<pre><code class='form-control'>"+JSON.stringify(response.outParameter,null,4)+"</code></pre>" +
                    "</div></div>" +
                    "</form>";
                BootstrapDialog.show({title : "MOCK",html:html,width:"50%",height:"60%"});
            }
        });
    });
    //详情
    $("#apiTable").on("click",".detail",function (event) {
        var rid = $(this).attr("rid");
        var url = "/pages/dms/sqlStatementDetail.html";
        $('#navbar').bootstrapNavbar("load",url,{id:rid});
    })
}

function intApiTreeTable() {
    var options = {
        id : "treeId",
        parentId : "treeParentId",
        pagination: true,
        showColumns : false,
        showRefresh : false,
        expandFirst : false,
        expandColumn : 1,
        url : "/dms/page",
        queryParamsType : "",
        sidePagination : 'server',//server:服务器端分页|client：前端分页
        pageList : [10,30,50,70,100],//可选择单页记录数
        columns : [
            {checkbox : true},
            {field : "namespace",title : "空间",align:"center"},
            {field : "name",title : "名字",align:"center"},
            {field : "shortId",title : "编号",align:"center"},
            /*
                        {field : "commandType",title : "类型",align:"center"},
                        {field : "returnType",title : "结果",align:"center"},
                        {field : "dynamicDataSourceKeys",title : "数据源",align:"center"},
            */
            {field : "enable",title : "状态",align:"center",width:"7%",formatter:function (value, row, index){
                    return value ? value == 1 ? "启用" : "禁用" : "禁用";
                }},
            {field : "updateBy",title : "修改人",align:"center",formatter: function (value, row, index){
                    return value ? value : row.createBy ? row.createBy : "";
                }},
            {field : "updateTime",title : "修改时间",align:"center",formatter: function (value, row, index){
                    return value ? new Date(value).format("yyyy-MM-dd HH:mm:ss") : row.createTime ? new Date(row.createTime).format("yyyy-MM-dd HH:mm:ss") : "";
                }},
            {field : "operate",title : "操作",align:"center",formatter : function (value, row, index) {
                    return "<button type='button' class='btn btn-link edit' rid='"+row.id+"'>编辑</button>" +
                        "<button type='button' class='btn btn-link mock' rid='"+row.id+"'>Mock</button>" +
                        "<button type='button' class='btn btn-link detail' rid='"+row.id+"'>详情</button>";
                }},
            {field : "id",title : "id",visible:false},
            {field : "uid",title : "UID",visible:false},
        ],
        queryParams : function(params){
            var json = $("#apiSearch").serializable();
            //忽略空值
            json =  Object.keys(json).reduce(function(acc, key) {
                if (json[key] !== null && json[key] !== undefined && json[key] !== '' && !(typeof json[key] === 'object' && Object.keys(json[key]).length === 0)) {
                    acc[key] = json[key];
                }
                return acc;
            }, {});
            //查询表达没有筛选项，或选表格中项，根据选中的树形菜单选中项查询
            if(Object.keys(json).length === 0){
                var id = $("#apiMenuSelectedId").val();
                if(id){
                    json.id = id;
                }
            }
            return $.extend({},(params ? params : {}),json);
        },
        responseHandler : function (response) {
            return {total : response.total ,rows : response.records};
        }
    };

    $("#apiTable").bootstrapTreeTable(options);
}